package com.tangdi.production.mpaychl.service.impl.bailian;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tangdi.production.mpaychl.base.service.BaseTranService;
import com.tangdi.production.mpaychl.service.impl.bailian.util.EnvironmentConstants;
import com.tangdi.production.mpaychl.service.impl.bailian.util.SecureUtil;
import com.tangdi.production.mpbase.constants.ExcepCode;
import com.tangdi.production.mpbase.constants.MsgCT;
import com.tangdi.production.mpbase.exception.TranException;
import com.tangdi.production.mpbase.util.ObjectUtil;

@Service("QUICK_Bailian")
public class BailianPayServiceImpl implements BaseTranService {
	private static final Logger logger = LoggerFactory.getLogger(BailianPayServiceImpl.class);
	
	private final static String  PAY_URL = EnvironmentConstants.BASE_URL + "/pay/v2/auth_pay_apply";
	
	@Override
	public Map<String, Object> execute(Map<String, Object> param) throws TranException {
		logger.info("进入自有跳转QUICK_Bailian处理接口 [{}]", param);
		
		// 校验参数
		valideData(param);
		
		try {
			String tradeRequest = getParamter(param);
			JSONObject jsonObject = JSON.parseObject(tradeRequest);
			tradeRequest = jsonObject.toJSONString();
			logger.info("tradeRequest:{}", tradeRequest);
			// 对交易请求参数进行加密
			Map<String,String> map = SecureUtil.encryptTradeInfo(EnvironmentConstants.MERCHANT_NO, tradeRequest, EnvironmentConstants.private_key, EnvironmentConstants.public_key);
			
			String response = postSend(PAY_URL,JSON.toJSONString(map));
			
			JSONObject responseJson = JSON.parseObject(response);
			
			String tradeResponse = SecureUtil.decryptTradeInfo(EnvironmentConstants.MERCHANT_NO, responseJson.getString("CER"), responseJson.getString("DATA"), responseJson.getString("SIGN"), EnvironmentConstants.private_key, EnvironmentConstants.public_key);
			logger.info("tradeResponse:{}", tradeResponse);
			JSONObject json = JSON.parseObject(tradeResponse);
			if (Objects.equals("00000000", json.get("responseCode"))){
				Map<String, Object> backMap = new HashMap<>();
				backMap.put("ordStatus", MsgCT.ORDSTATUS_PROCESSING);
				backMap.put("msg", "成功");
				return backMap;
			} else {
				Map<String, Object> backMap = new HashMap<>();
				backMap.put("ordStatus", MsgCT.ORDSTATUS_FAIL);
				backMap.put("msg", json.get("responseDesc"));
				return backMap;
			}
			
		} catch (Exception e){
			logger.error("QUICK_Bailian支付失败:{}", e.getMessage(), e);
			throw new TranException("900002",e.getMessage());
		}
		
	}

	private String getParamter(Map<String, Object> param){
		
		String reqData = "" + param.get("reqData");
		JSONObject reqJson = JSON.parseObject(reqData);
		
		String payAmt = ObjectUtil.getString(param.get("payAmt"));
		logger.info("支付金额[{}分]", payAmt);
		
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("userNo", reqJson.get("outUserNo"));
		request.put("requestTime", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
		request.put("outTradeNo", param.get("prdOrdNo"));
		request.put("tradeAmount", payAmt);//单位为分
		request.put("tradeCurrency","CNY");
		request.put("returnInfo", "");
		request.put("extendInfo","");
		request.put("riskInfo","");
		request.put("returnUrl", param.get("front_url") == null ? EnvironmentConstants.return_url : "" + param.get("front_url"));
		request.put("notifyAddress", EnvironmentConstants.notify_url);
		request.put("bankCode", reqJson.get("bankCode"));
		request.put("cardType","DC");
		request.put("cardNo", reqJson.get("cardNo"));
		request.put("cardExp","");
		request.put("cardCvv","");
		request.put("holderName", reqJson.get("holderName"));
		request.put("holderIdType","IDCARD");
		request.put("holderIdNo", reqJson.get("holderIdNo"));
		request.put("holderMobile", reqJson.get("holderMobile"));
		
		return JSON.toJSONString(request);
	}
	
	private String postSend(String url,String argsJson) throws Exception {
		HttpClient httpclient = new DefaultHttpClient();
		logger.info("url:{}", url);
		HttpPost httpPost = new HttpPost(url);
		
		StringEntity entity = new StringEntity(argsJson);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/text");
		httpPost.setEntity(entity);
		
		logger.info("request:{}", argsJson);
		HttpResponse response = httpclient.execute(httpPost);
		HttpEntity resEntity = response.getEntity();
        String resp = EntityUtils.toString(resEntity);
        logger.info("response:{}", resp);
        return resp;
	}
	
	private void valideData(Map<String, Object> paramMap) throws TranException{
		if (paramMap == null || paramMap.isEmpty()){
			logger.error("参数不能为空");
			throw new TranException(ExcepCode.EX900001,"参数不能为空");
		}
		
		String reqData = "" + paramMap.get("reqData");
		JSONObject reqJson = JSON.parseObject(reqData);
		
		if (StringUtils.isBlank(reqData)){
			logger.error("请求参数不能为空");
			throw new TranException(ExcepCode.EX900001,"请求参数不能为空");
		}
		if (StringUtils.isBlank(reqJson.getString("payAmt"))){
			logger.error("充值金额不能为空");
			throw new TranException(ExcepCode.EX900001,"充值金额不能为空");
		}
/*		if (StringUtils.isBlank(reqJson.getString("outUserNo"))){
			logger.error("终端客户号不能为空");
			throw new TranException(ExcepCode.EX000101,"终端客户号不能为空");
		}*/
		if (StringUtils.isBlank(reqJson.getString("bankCode"))){
			logger.error("银行编号不能为空");
			throw new TranException(ExcepCode.EX900001,"银行编号不能为空");
		}
		if (StringUtils.isBlank(reqJson.getString("cardNo"))){
			logger.error("银行卡号不能为空");
			throw new TranException(ExcepCode.EX900001,"银行卡号不能为空");
		}
		if (StringUtils.isBlank(reqJson.getString("holderName"))){
			logger.error("持卡人姓名不能为空");
			throw new TranException(ExcepCode.EX900001,"持卡人姓名不能为空");
		}
		if (StringUtils.isBlank(reqJson.getString("holderIdNo"))){
			logger.error("持卡人身份证号不能为空");
			throw new TranException(ExcepCode.EX900001,"持卡人身份证号不能为空");
		}
		if (StringUtils.isBlank(reqJson.getString("holderMobile"))){
			logger.error("绑定手机号不能为空");
			throw new TranException(ExcepCode.EX900001,"绑定手机号不能为空");
		}
	}
}
